package com.powerhua.core.base.dao;

import com.powerhua.core.base.BaseModelCacheManager;
import com.powerhua.core.base.bean.IField;
import com.powerhua.core.base.bean.IModel;
import com.powerhua.core.utils.CommonUtils;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.RowCallbackHandler;

/**
 *
 * @author Brian.Xie 
 */
public class ObjectDao extends CommonDao {

    private static final Log LOG = LogFactory.getLog(ObjectDao.class);

    public String getObjById(Map map, String modelId) {
        IModel model = BaseModelCacheManager.getInstance().getModel(modelId);
        if (!checkModel(model)) {
            return "";
        }

        final IField pkField = model.getPk();
        String pkValue = "";
        String[] pkValueObj = (String[]) map.get(pkField.getName());
        if (pkValueObj != null) {
            pkValue = pkValueObj[0];
        } else {
            return "";
        }

        StringBuffer sql = new StringBuffer();
        sql.append("select * from ");
        sql.append(model.getModelTable());
        sql.append(" where ");
        sql.append(model.getPk().getName());
        sql.append("=?");

        final StringBuffer result = new StringBuffer();
        final Map fields = model.getFields();
        jdbcTemplate.query(sql.toString(),
                new Object[]{pkValue}, new RowCallbackHandler() {

            @Override
            public void processRow(ResultSet rs) throws SQLException {
                Iterator<Entry<String, IField>> itr = fields.entrySet().iterator();
                result.append("[");
                result.append("['");
                result.append(pkField.getName());
                result.append("','");
                result.append(getResultSetValue(rs, pkField.getType().toLowerCase(), pkField.getName()));
                result.append("']");
                if (itr.hasNext()) {
                    result.append(",");
                }
                while (itr.hasNext()) {
                    Entry<String, IField> entry = itr.next();
                    IField field = entry.getValue();
                    result.append("['");
                    result.append(field.getName());
                    result.append("','");
                    result.append(getResultSetValue(rs, field.getType().toLowerCase(), field.getName()));
                    result.append("']");
                    if (itr.hasNext()) {
                        result.append(",");
                    }
                }
                result.append("]");
                LOG.debug("result is " + result.toString());
            }

            /**
             * 
             * @param rs
             * @param type
             * @param colName
             * @return
             * @throws java.sql.SQLException
             */
            private String getResultSetValue(ResultSet rs, String type, String colName) throws SQLException {
                String result = "";
                if ("timestamp".equals(type)) {
                    result = CommonUtils.getDateTimeFormat(rs.getTimestamp(colName));
                } else if ("date".equals(type)) {
                    result = CommonUtils.getDateFormat(rs.getTimestamp(colName));
                } else if ("decimal".equals(type)) {
                    result = rs.getBigDecimal(colName).toString();
                } else if ("varchar".equals(type)) {
                    result = rs.getString(colName);
                } else if ("integer".equals(type) || "int".equals(type)) {
                    result = "" + rs.getInt(colName);
                } else if ("bigint".equals(type)) {
                    result = "" + rs.getLong(colName);
                } else if ("float".equals(type)) {
                    result = "" + rs.getFloat(colName);
                } else if ("double".equals(type)) {
                    result = "" + rs.getDouble(colName);
                } else {
                    LOG.error("Not support type");
                    throw new SQLException("Not support type. type:" + type);
                }
                return result;
            }
        });

        return result.toString();
    }
}
